import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { routerRedux,Link } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Badge,
  Popconfirm,
  Divider,
  Table,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import defaultAvatar from '../../assets/admin_logo.png';
import styles from './Banner.less';
import EditTableCell from './EditTableCell';
import G from '../../utils/g';
import GoodsModal from '../Sales/GoodsModal';


const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];


@connect(({ indexGroupGoods, loading }) => ({
  indexGroupGoods,
  loading: loading.models.indexGroupGoods,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    addInputValue: '',
    checkedGroupList: [],
    selectedGoods : []
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    this.id = G.getUrlValue('id', location.search);
    if(typeof this.id == 'undefined'){
      notification.error({
        message: '页面错误',
        description: '分组ID不能为空',
      });
    }else{
      dispatch({
        type: 'indexGroupGoods/fetch',
        payload : {
          groupId : this.id
        }
      });
    }

    /*dispatch({
     type : 'indexGroupGoods/fetchGroup',
     });*/
  }
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });

  };
  changeSelectedGoods = (goods)=>{  //从弹框中获取到选中的商品
    console.log("goods",goods);
    this.setState({
      selectedGoods : goods
    });
  };
  removeSelected = (id)=>{  //移除选中的商品

    if(typeof id == 'undefined'){
      console.error('被移除的商品ID为空');
      return false;
    }
    let selectedGoods = [...this.state.selectedGoods];
    const result = selectedGoods.filter(v => v.id != id);
    //console.log('selectedGoods',selectedGoods, result);
    this.setState({
      selectedGoods : result
    });

  };
  bindDelete = (id)=>{
    this.props.dispatch({
      type : 'indexGroupGoods/deleteItem',
      payload : {
        id : this.id,
        goodsIds : [id]
      }
    }).then(res=>{
      if(res){
        message.success('移除成功');
      }else{
        message.error('移除失败');
      }
    })
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      groupId : this.id,
      startIndex: (pagination.current - 1) * pagination.pageSize, //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'indexGroupGoods/fetch',
      payload: params,
    });
  };

  onCellChange = (key, dataIndex) => {
    return (value) => {
      console.log(value);
      if(isNaN(value)){
        message.error('权重必须为0-100的数值');
        return false;
      }else if(Number(value) > 100 || Number(value) < 0){
        message.error('权重必须为0-100的数值');
        return false;
      }
      this.props.dispatch({
        type : 'indexGroupGoods/changeWeight',
        payload : {
          groupId : this.id,
          goodsId : key,
          weight : Number(value),
        }
      });
    };
  };
  changeStatus = (item)=>{
    const {  id , status } = item;
    console.log('item',item);
    this.props.dispatch({
      type : 'indexGroupGoods/changeStatus',
      payload : {
        id,
        status : status ? 0 : 1
      }
    })
  };

  renderForm() {
    return this.renderSimpleForm();
  }

  handleSureSelect = ()=>{
    //确认选中的商品
    console.log(this.state.selectedGoods);
    this.props.dispatch({
      type : 'indexGroupGoods/addGoods',
      payload : {
        id : this.id,
        goods : this.state.selectedGoods
      }
    }).then(res=>{
      this.setState({
          modalVisible : false,
          selectedGoods : [], //清空选中商品
        });
      if(res){
        message.success('添加成功');
      }else{
        message.error('添加失败');
      }
    });
  }

  render() {
    const { indexGroupGoods: { data, group }, loading } = this.props;
    const { selectedRows, modalVisible, addInputValue, checkedGroupList, selectedGoods } = this.state;

    //console.log(data);
    const columns = [
      {
        title: '商品',
        dataIndex : 'name'
      },
      {
        title: '图片',
        dataIndex: 'imgs',
        render:val=>{
          return <img src={val[0] || defaultAvatar} width="60" height={60} />
        }
      },
      {
        title: '价格',
        dataIndex : 'min_price'
      },
      {
        title: '划线价',
        dataIndex : 'line_price'
      },
      {
        title: '权重',
        dataIndex: 'weight',
        render: (val, record) =>{
          return <EditTableCell
            value={val || '0'}
            onChange={this.onCellChange(record.id, 'weight')}
          />
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        render : (val) =>{
          return <Badge status={val ? 'success' : 'error'} text={val ? '已上架' : '已下架'} />
        }
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <Popconfirm title="你确定要移除该商品？" okText="确定" cancelText="取消" onConfirm={()=>{ this.bindDelete(record.id) }}>
              <a href="">移除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout
        title="分组商品管理"
      >
        <Card bordered={false}>
              <Button
                 onClick={this.handleModalVisible}
              >
                添加商品
              </Button>
          <div className={styles.tableList}  style={{marginTop:'16px'}}>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowSelection= {null}
            />
          </div>
        </Card>
        <GoodsModal
          type = "groupGoods"
          dispatch={this.props.dispatch}
          modalVisible={modalVisible}
          handleHide={this.handleModalVisible}
          selectedRows = {selectedGoods}
          changeSelectedGoods = {this.changeSelectedGoods}
          handleOk = { this.handleSureSelect}
        />
      </PageHeaderLayout>
    );
  }
}
